package com.bootdo.clouddo.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;


@Component
public class QiniuImageUploader {
	
	private static Logger logger = LoggerFactory.getLogger(QiniuImageUploader.class);
	
	
	public static String bucket;
	public static String domain;
	public static String accessKey;
	public static String secretKey;
	
	public QiniuImageUploader() {}
	
	private QiniuImageUploader(Auth auth) {
		this.auth = auth;
	}
	
	@Value("${qiniu.bucket}")
	public void setBucket(String bucket) {
		QiniuImageUploader.bucket = bucket;
	}
	
	@Value("${qiniu.domain}")
	public void setDomain(String domain) {
		QiniuImageUploader.domain = domain;
	}
	
	@Value("${qiniu.accessKey}")
	public void setAccessKey(String accessKey) {
		QiniuImageUploader.accessKey = accessKey;
	}

	@Value("${qiniu.secretKey}")
	public void setSecretKey(String secretKey) {
		QiniuImageUploader.secretKey = secretKey;
	}
	
	private static Object locker = new Object();
    
    private Auth auth;
    
    private static QiniuImageUploader uploader = null;
    
    public static QiniuImageUploader newInstance() {
    	if(uploader == null)
    		synchronized (locker) {
				if(uploader == null) {
					uploader = new QiniuImageUploader(Auth.create(accessKey, secretKey));
				}
			}
    	return uploader;
    }

    public String getUpTokenCommon() {
        return auth.uploadToken(bucket);
    }


	/**
     * 封装文件相关信息
     * @author bukaa
     *
     */
    public class MyRet {
        public long fsize;
        public String key;
        public String hash;
        public int width;
        public int height;
        public int error;
        public String url;
    }

    /**
     * 通过后台上传文件至七牛云
     * @param imageData 即将上传的文件的字节
     * @param rename 文件的名称（key）
     * @param type 文件类型， eg:common
     * @return
     */
    public MyRet upload(byte[] imageData, String rename) {
    	//构造一个带指定Zone对象的配置类 Zone.zone2-->华南区
    	Configuration cfg = new Configuration(Zone.zone2());
        UploadManager uploadManager = new UploadManager(cfg);
        MyRet ret = null;
        try {
            Response res = uploadManager.put(imageData, rename, getUpTokenCommon());
            logger.info(res.bodyString());
            ret = res.jsonToObject(MyRet.class);
            ret.key =  rename;
            ret.url = getUrl(ret.key, 0);
            ret.error = 0;
        } catch (QiniuException e) {
            Response r = e.response;
            try {
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                e1.printStackTrace();
            }
        }
        return ret;
    }
    
    /**
     * 通过后台上传文件至七牛云
     * @param file 即将上传的文件
     * @param rename 文件的名称（key）
     * @param type 文件类型， eg:common
     * @return
     */
    public MyRet upload(File file, String rename) {
    	//构造一个带指定Zone对象的配置类 Zone.zone2-->华南区
    	Configuration cfg = new Configuration(Zone.zone2());
        UploadManager uploadManager = new UploadManager(cfg);
        MyRet ret = null;
        try {
            Response res = uploadManager.put(file, rename, getUpTokenCommon());
            logger.info(res.bodyString());
            ret = res.jsonToObject(MyRet.class);
            ret.key =  rename;
            ret.url = getUrl(ret.key, 0);
            ret.error = 0;
        } catch (QiniuException e) {
            Response r = e.response;
            try {
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                e1.printStackTrace();
            }
        }
        return ret;
    }
    
    /**
     * 获取文件下载的URL
     * @param key 文件的名称（key）
     * @param type 文件类型， eg:common
     * @param expireSeconds URL过期时间，公开文件URL无过期时间
     * @return
     */
    public String getUrl(String key, long expireSeconds) {
		String encodedFileName = null;
		try {
			encodedFileName = URLEncoder.encode(key, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return String.format("%s/%s", domain, encodedFileName);	}

}
